﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using ARSys.Connector;
using ARSys.Entity;
using Wicresoft.Logger;
using Wicresoft.Message;
using Wicresoft.Task.Common;

namespace Wicresoft.Task.ARNotice
{
    public class ARSysEmail : Wicresoft.Task.Common.IntervalTask
    {
        private static readonly string ARServer = ConfigurationManager.AppSettings["ARServer"];
        private static readonly string ARUid = ConfigurationManager.AppSettings["ARUid"];
        private static readonly string ARPwd = ConfigurationManager.AppSettings["ARPwd"];
        
        protected override void Execute()
        {
            if (EmailFactory.Bag == null)
                EmailFactory.Bag = Bag;

            using (ARSysContext dc = new ARSysContext())
            {
                var source = dc.Emails.Where(p => p.IsSent == 0).ToArray();
                Log.Debug(this.Name, "ARSysContext.Emails.Count: {0}", source.Length);


                if (source.Length == 0)
                    return;

                using (ARSysProxy px = new ARSysProxy(ARServer, ARUid, ARPwd))
                {
                    foreach (var armail in source)
                    {
                        try
                        {
                            // 将邮件置入数据库，待发送
                            EmailTemplate tpl = EmailFactory.CreateEmailTemplate(armail, dc);
                            SmtpHelper.SendEmail(tpl.Subject, tpl.Body, Bag.MailFrom, tpl.To, tpl.Cc, tpl.Bcc, tpl.ReplyTo, tpl.Priority);
                            Log.Debug(this.Name, "ProceedEmail {0}", armail.RequestId);

                            // 设置邮件为已发
                            armail.IsSent = 1;
                            px.SetEntry(armail);
                            Log.Debug(this.Name, "SetEmail {0}", armail.RequestId);
                        }
                        catch (Exception e)
                        {
                            Log.Exception(this.Name, e);
                        }
                    }
                }

            }
        }

    }
}
